import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import Cookies from 'js-cookie'
import { login, register, getCurrentUser } from '@/api/user'

export const useUserStore = defineStore('user', () => {
  // 状态
  const token = ref(Cookies.get('token') || '')
  const userInfo = ref(null)

  // 计算属性
  const isLoggedIn = computed(() => !!token.value)
  const isAdmin = computed(() => userInfo.value?.role === 'ADMIN')

  // 设置token
  const setToken = (newToken) => {
    token.value = newToken
    if (newToken) {
      Cookies.set('token', newToken, { expires: 7 }) // 7天过期
    } else {
      Cookies.remove('token')
    }
  }

  // 设置用户信息
  const setUserInfo = (info) => {
    userInfo.value = info
  }

  // 登录
  const loginAction = async (loginForm) => {
    try {
      const response = await login(loginForm)
      const { token: newToken, user } = response.data

      setToken(newToken)
      setUserInfo(user)

      return response
    } catch (error) {
      throw error
    }
  }

  // 注册
  const registerAction = async (registerForm) => {
    try {
      const response = await register(registerForm)
      return response
    } catch (error) {
      throw error
    }
  }

  // 获取当前用户信息
  const fetchUserInfo = async () => {
    try {
      const response = await getCurrentUser()
      setUserInfo(response.data)
      return response
    } catch (error) {
      // 如果获取用户信息失败，清除token
      logout()
      throw error
    }
  }

  // 登出
  const logout = () => {
    setToken('')
    setUserInfo(null)
  }

  // 初始化用户信息
  const initUserInfo = async () => {
    if (token.value && !userInfo.value) {
      try {
        await fetchUserInfo()
      } catch (error) {
        console.error('初始化用户信息失败:', error)
      }
    }
  }

  return {
    // 状态
    token,
    userInfo,

    // 计算属性
    isLoggedIn,
    isAdmin,

    // 方法
    setToken,
    setUserInfo,
    loginAction,
    registerAction,
    fetchUserInfo,
    logout,
    initUserInfo
  }
})